<?php
// app/websocket/ChatHandler.php
namespace app\websocket;
use adminmatrix\swoole\Websocket;

class ChatHandler extends Websocket
{
    // 连接建立事件 (参数名必须为 $server, $request)
    public function onOpen($server, $request)
    {
        echo "Client {$request->fd} Connected\n";
        $this->push($request->fd, json_encode(['msg' => 'Welcome!']));
    }

    // 接收消息事件 (参数名必须为 $server, $frame)
    public function onMessage($server, $frame)
    {
        $data = json_decode($frame->data, true);
        // 广播消息给所有客户端
        foreach ($server->connections as $fd) {
            $this->push($fd, json_encode([
                'from' => 'Server',
                'content' => $data['content']
            ]));
        }
    }

    // 连接关闭事件
    public function onClose($server, $fd)
    {
        echo "Client {$fd} Closed\n";
    }
}